<template>
  <div class="main-content">
    <div class="main-content-top">
      <div class="userInfo">
        <div class="title">用户信息</div>
        <div class="info">
          <div class="info-item">
            <div class="info-item-name">姓名：</div>
            <div class="info-item-content">{{ userData.answer_name }}</div>
          </div>
          <div class="info-item">
            <div class="info-item-name">手机：</div>
            <div class="info-item-content">{{ userData.phone }}</div>
          </div>
          <div class="info-item">
            <div class="info-item-name">参与项目：</div>
            <div v-if="userData.group" class="info-item-content">{{ userData.group.group_name }}</div>
            <div v-else class="info-item-content">{{ userData.zoom.zoom_name }}</div>
          </div>
          <div class="info-item">
            <div class="info-item-name">参与时间：</div>
            <div class="info-item-content">{{ userData.create_time }}</div>
          </div>

        </div>
      </div>
      <div class="analysis">
        <div class="title">
          <div>智学报告</div>
          <div v-if="isZoom">
            <span>报告选择：</span>
            <el-select v-model="value" placeholder="请选择" size="mini" @change="changeZuJuan">
              <el-option
                v-for="(item,index) in options"
                :key="item.group_id"
                :label="'报告'+(index+1)"
                :value="index"
              />
            </el-select>
          </div>
        </div>
        <div v-if="isHasReport == 0" class="analysis-content">
          <div class="canvns">
            <div id="leiDaTu" class="echart" style="width: 100%;height: 100%;">1</div>
          </div>
          <div class="collapse">
            <div class="showDig" @click="showDig">数据报表</div>
            <el-collapse :accordion="true" class="showCollapse">
              <el-collapse-item v-for="(item,index) in rateList" :key="index">
                <template slot="title">
                  {{ item.rate }}
                </template>
                <div>{{ item.content }}</div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
        <!-- //没分值 -->
        <div v-else class="analysis-content">
          <div class="noFen">
            <div class="showDig2" @click="showDig">数据报表</div>
            <div>
              <div v-if="baoGaoData.hasBaoGao" style="height:138px">{{ baoGaoData.content }}</div>
              <el-input
                v-else
                v-model="baoGaoData.content"
                type="textarea"
                :rows="6"
                placeholder="请点击查看数据报告，录入报告分析内容。"
              />
            </div>
            <div class="tipsText">注意：此报告设置后不能更改</div>
            <div class="bottomBtn">
              <el-button v-if="!baoGaoData.hasBaoGao" v-pageRoles="['5fae39127d789']" type="primary" size="small" class="saveBtn" @click="saveBaoGao">保存</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-pageRoles="['5fae39127d789']" class="main-content-bottom">
      <div class="title">课程引流</div>
      <div class="drainage">
        <div class="curriculumNum">
          课程数量:
          <el-radio-group v-model="radio" class="courseNum">
            <el-radio :label="1">1</el-radio>
            <el-radio :label="2">2</el-radio>
            <el-radio :label="3">3</el-radio>
          </el-radio-group>
        </div>
        <div class="course">
          <div v-for="(item,index) in radio" :key="index" class="courseItem">
            <el-form :ref="`ruleForm${item}`" :model="ruleForm[index]" :rules="rules[index]" label-width="100px" class="demo-ruleForm">
              <el-form-item :label="'课程'+Serial[index]+'：'" />
              <el-form-item label="课程名称：" prop="course">
                <el-input v-model="ruleForm[index].course" />
              </el-form-item>

              <el-form-item label="课程简介：" prop="course_introduction">
                <el-input v-model="ruleForm[index].course_introduction" type="textarea" />
              </el-form-item>
              <el-form-item label="图片简介：" prop="picture">

                <upload
                  ref="upload2"
                  :config="config2"
                  :upload-id="'uploadId'+index+1"
                  :index="index"
                  :urlnow="{url:ruleForm[index].picture}"
                  @filepath="filepath2(arguments,index)"
                />

              </el-form-item>
              <div class="tip">请尽量上传宽高比例为16:9的图片,以达到最佳预览效果</div>
              <el-form-item label="课程链接：" prop="url">
                <el-input v-model="ruleForm[index].url" />
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div style="text-align: right;">
          <el-button type="primary" @click="submitForm()">生成报告</el-button>
        </div>
      </div>
    </div>
    <el-dialog title="智测报表" :visible.sync="dialogTableVisible">
      <el-table :data="showQuestionAnswerList">

        <el-table-column label="题目">
          <template slot-scope="scope">
            {{ scope.row.content }}
          </template>
        </el-table-column>
        <el-table-column label="类型">
          <template slot-scope="scope">
            <div v-if="scope.row.question_case === 1"> 单选</div>
            <div v-if="scope.row.question_case === 2">多选</div>
            <div v-if="scope.row.question_case === 3">填空</div>
          </template>
        </el-table-column>
        <template>
          <el-table-column label="选项">
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.options" :key="index">
                <div v-if="scope.row.question_case == 1 || scope.row.question_case == 2">
                  {{ item.is_other == 1?'其他': item.option }}
                </div>
                <div v-if="scope.row.question_case == 3">
                  无
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="正确答案">
            <template slot-scope="scope">
              <div v-if="isHasReport == 0">
                <div v-for="(item1,index1) in scope.row.options" :key="index1">
                  <div v-if="item1.option_score>0">{{ item1.is_other == 1?'其他': item1.option }}</div>
                </div>
              </div>
              <div v-else style="padding-left:15px">
                无
              </div>
            </template>
          </el-table-column>
          <el-table-column label="回答情况">
            <template slot-scope="scope">
              <div v-if="scope.row.question_case == 1 || scope.row.question_case == 2">
                <div v-for="(item2,index2) in scope.row.options" :key="index2">
                  <div v-if="item2.isChecked">{{ item2.is_other == 1?'其他': item2.option }}</div>
                </div>
              </div>
              <div v-if="scope.row.question_case ==3">
                {{ scope.row.remark }}
              </div>

            </template>
            <!-- <template v-if="scope.row.question_case == 3" slot-scope="scope">
              {{ scope.row.remark }}
            </template> -->
          </el-table-column>
        </template>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import echarts from 'echarts'
import upload from '@/components/upload/index'
import { uploadConfig2 } from '@/components/upload/config/upload1'
import { courseSaveAlls, createreport, getAnswerSheet, addNdreport } from '@/api/course'
import { getQuestionInfos } from '@/api/question'
export default {
    name: 'PreviewReport',
    components: {
        upload
    },
    props: {},
    data() {
        return {
            isHasReport: 0, // 是否有报告
            baoGaoData: { // 手动报告数据
                content: '',
                phone: '',
                group_id: ''
            },
            rate_num: 0, // 级别
            userData: {
                answer_name: '',
                phone: '',
                group: {
                    group_name: ''
                },
                create_time: ''
            }, // 用户
            echarData: [],
            rateList: [],
            Serial: ['一', '二', '三'],
            filepath2li: [],
            config2: uploadConfig2,
            isVerified: false,
            radio: 1,
            ruleForm: [{
                course: '',
                course_introduction: '',
                url: '',
                picture: '',
                fileName: [{
                    filepath: ''
                }]
            }, {
                course: '',
                course_introduction: '',
                url: '',
                picture: '',
                fileName: [{
                    filepath: ''
                }]
            }, {
                course: '',
                course_introduction: '',
                url: '',
                picture: '',
                fileName: [{
                    filepath: ''
                }]
            }],
            questionList: [], // 问题列表
            showQuestionAnswerList: [], // 数组答题拼接表列表
            rules: [{
                course: [
                    { required: true, message: '请输入课程名称', trigger: 'blur' }
                ],
                url: [
                    { required: true, message: '请输入课程链接', trigger: 'blur' }
                ],
                course_introduction: [
                    { required: true, message: '请填写课程简介', trigger: 'blur' }
                ],
                picture: [
                    { required: true, message: '请上传图片简介', trigger: 'change' }
                ]
            },
            {
                course: [
                    { required: true, message: '请输入课程名称', trigger: 'blur' }
                ],
                url: [
                    { required: true, message: '请输入课程链接', trigger: 'blur' }
                ],
                course_introduction: [
                    { required: true, message: '请填写课程简介', trigger: 'blur' }
                ],
                picture: [
                    { required: true, message: '请上传图片简介', trigger: 'change' }
                ]
            }, {
                course: [
                    { required: true, message: '请输入课程名称', trigger: 'blur' }
                ],
                url: [
                    { required: true, message: '请输入课程链接', trigger: 'blur' }
                ],
                course_introduction: [
                    { required: true, message: '请填写课程简介', trigger: 'blur' }
                ],
                picture: [
                    { required: true, message: '请上传图片简介', trigger: 'change' }
                ]
            }],
            options: [],
            value: 0,
            isZoom: false,
            dialogTableVisible: false
        }
    },
    computed: {},
    beforeCreate() {
    // 生命周期钩子：组件实例刚被创建，组件属性计算之前，如 data 属性等
    },
    created() {
    // 生命周期钩子：组件实例创建完成，属性已绑定，但 DOM 还未生成，el 属性还不存在
    // 初始化渲染页面
        var queryData = {
            group_id: this.$route.query.group_id,
            phone: this.$route.query.phone,
            respondent_id: this.$route.query.respondent_id
        }
        if (this.$route.query.zoomGroup) {
            this.isZoom = true
            console.log('获取组卷：', JSON.parse(this.$route.query.zoomGroup))
            this.options = JSON.parse(this.$route.query.zoomGroup)
            queryData = {
                group_id: this.options[this.value].group_id,
                phone: this.$route.query.phone,
                respondent_id: this.$route.query.respondent_id,
                zoom_id: this.$route.query.group_id
            }
        }

        createreport(queryData).then(res => {
            console.log(res)
            if (res.code == 200) {
                this.isHasReport = res.data.noreport
                this.userData = res.data.student

                this.echarData = res.data.data
                this.rate_num = res.data.rate_num
                if (res.data.course.length !== 0) {
                    this.radio = res.data.course.length
                    var arr = [{
                        course: '',
                        course_introduction: '',
                        url: '',
                        picture: '',
                        fileName: [{
                            filepath: ''
                        }]
                    }, {
                        course: '',
                        course_introduction: '',
                        url: '',
                        picture: '',
                        fileName: [{
                            filepath: ''
                        }]
                    }, {
                        course: '',
                        course_introduction: '',
                        url: '',
                        picture: '',
                        fileName: [{
                            filepath: ''
                        }]
                    }]
                    for (let index = 0; index < res.data.course.length; index++) {
                        const element = res.data.course[index]
                        element.fileName = [{
                            filepath: ''
                        }]
                        arr[index] = element
                    }
                    this.ruleForm = arr
                    console.log('有数据渲染：', this.ruleForm)
                }
                if (this.isHasReport === 1) {
                    if (!res.data.data) {
                        return
                    }
                    if (res.data.data != '') {
                        res.data.data.hasBaoGao = true
                    }
                    this.baoGaoData = res.data.data
                    return
                }
                this.$nextTick(function() {
                    this.drawPie('leiDaTu')
                })
            }
        })
        console.log('baoGaoData.hasBaoGao', this.baoGaoData.hasBaoGao)
    },
    beforeMount() {
    // 生命周期钩子：模板编译/挂载之前
    },
    mounted() {
    // 生命周期钩子：模板编译、挂载之后（此时不保证已在 document 中）
    },
    methods: {
    // 选择组卷
        changeZuJuan() {
            //   console.log({
            //     group_id: this.options[this.value].group_id,
            //     phone: this.$route.query.phone,
            //     respondent_id: this.$route.query.respondent_id,
            //     zoom_id: this.$route.query.group_id
            //   })
            createreport({
                group_id: this.options[this.value].group_id,
                phone: this.$route.query.phone,
                respondent_id: this.$route.query.respondent_id,
                zoom_id: this.$route.query.group_id
            }).then(res => {
                console.log(res)
                if (res.code == 200) {
                    this.isHasReport = res.data.noreport
                    this.userData = res.data.student
                    this.echarData = res.data.data
                    this.rate_num = res.data.rate_num
                    if (res.data.course.length !== 0) {
                        this.radio = res.data.course.length
                        var arr = [{
                            course: '',
                            course_introduction: '',
                            url: '',
                            picture: '',
                            fileName: [{
                                filepath: ''
                            }]
                        }, {
                            course: '',
                            course_introduction: '',
                            url: '',
                            picture: '',
                            fileName: [{
                                filepath: ''
                            }]
                        }, {
                            course: '',
                            course_introduction: '',
                            url: '',
                            picture: '',
                            fileName: [{
                                filepath: ''
                            }]
                        }]
                        for (let index = 0; index < res.data.course.length; index++) {
                            const element = res.data.course[index]
                            element.fileName = [{
                                filepath: ''
                            }]
                            arr[index] = element
                        }
                        this.ruleForm = arr
                    } else {
                        this.radio = 1
                        var arr = [{
                            course: '',
                            course_introduction: '',
                            url: '',
                            picture: '',
                            fileName: [{
                                filepath: ''
                            }]
                        }, {
                            course: '',
                            course_introduction: '',
                            url: '',
                            picture: '',
                            fileName: [{
                                filepath: ''
                            }]
                        }, {
                            course: '',
                            course_introduction: '',
                            url: '',
                            picture: '',
                            fileName: [{
                                filepath: ''
                            }]
                        }]
                        this.ruleForm = arr
                    }
                    if (this.isHasReport === 1) {
                        if (!res.data.data) {
                            return
                        }
                        if (res.data.data != '') {
                            res.data.data.hasBaoGao = true
                        }
                        this.baoGaoData = res.data.data
                        return
                    }
                    this.$nextTick(function() {
                        this.drawPie('leiDaTu')
                    })
                }
            })
        },
        // 手动输入报告
        saveBaoGao() {
            if (this.baoGaoData.content == '') {
                return this.$message.error('报告不能为空')
            }
            this.baoGaoData.phone = this.userData.phone
            this.baoGaoData.group_id = this.$route.query.group_id
            this.baoGaoData.respondent_id = this.$route.query.respondent_id
            if (this.isZoom) {
                this.baoGaoData.group_id = this.options[this.value].group_id
                this.baoGaoData.zoom_id = this.$route.query.group_id
            }
            addNdreport(this.baoGaoData).then(res => {
                if (res.code === 200) {
                    console.log(res)
                    this.baoGaoData = res.data
                    this.baoGaoData.hasBaoGao = true
                    this.$message({
                        type: 'success',
                        customClass: 'customClass',
                        message: '保存成功!'
                    })
                }
            })
        },
        filepath2(param, index) {
            console.log(param)
            this.ruleForm[index].picture = param[1] + param[0]
            if (this.ruleForm[index].picture) {
                console.log('有上传的图片')
                this.$refs[`ruleForm${index + 1}`][0].clearValidate('picture')
                delete this.$refs[`ruleForm${index + 1}`][0].rules.picture
                console.log(this.$refs[`ruleForm${index + 1}`][0].rules)
            }
            this.ruleForm[index].fileName[0].filepath = param[0]
            //   this.filepath2li.push([{ filepath: param[0] }])
            console.log('选择的图片', this.ruleForm, index)
        },
        drawPie() {
            const charts = echarts.init(document.getElementById('leiDaTu'))
            var bb = []
            var cc = []
            this.rateList = []
            this.echarData.forEach(el => {
                bb.push({
                    max: 100,
                    name: el.dimension
                })
                cc.push(el.score)
                this.rateList.push({
                    rate: el.dimension + ' : ' + el.rate,
                    content: el.content
                })
            })
            console.log('bb', bb)
            console.log('cc', cc)
            var option = {
                title: {
                    link: 'https://www.baidu.com',
                    target: 'blank',
                    textAlign: 'left'

                },
                tooltip: {
                    formatter: function(a) {
                        var name = bb
                        var str = a.name + '<br>'
                        var data = a.value
                        for (var i = 0; i < name.length; i++) {
                            str += name[i].name + '  ' + ((data[i])) + '% <br>'
                        }
                        return str
                    }
                }, // 提示层
                legend: {
                    data: ['name1']
                },
                radar: {
                    splitNumber: this.rate_num,
                    name: {
                        textStyle: {
                            color: '#fff', // 字体颜色
                            backgroundColor: '#999', // 背景色
                            borderRadius: 3, // 圆角
                            padding: [3, 5] // padding
                        }
                    },
                    center: ['50%', '50%'],
                    radius: '60%',
                    startAngle: 270,
                    indicator: bb
                },
                series: [{
                    name: '测试标题名字',
                    type: 'radar',
                    data: [{
                        value: cc,
                        name: '测试结果(百分比)'
                    }]
                }]
            }
            console.log('图形配置', option)
            charts.setOption(option)
        },
        submitForm() {
            for (let i = 0; i < this.radio; i++) {
                this.$refs[`ruleForm${i + 1}`][0].validate((valid) => {
                    if (valid) {
                        this.isVerified = true
                    } else {
                        this.isVerified = false
                        return false
                    }
                })
            }
            console.log('是否通过验证', this.isVerified)
            var formDataArray = []
            var id = this.$route.query.group_id
            if (this.isZoom) {
                id = this.options[this.value].group_id
            }
            if (this.isVerified) {
                for (let i = 0; i < this.radio; i++) {
                    var iiu = JSON.parse(JSON.stringify(this.ruleForm[i]))
                    delete iiu.fileName
                    if (this.isZoom) {
                        iiu.zoom_id = this.$route.query.group_id
                        iiu.fk_id = this.options[this.value].group_id
                    } else {
                        iiu.fk_id = id
                        delete iiu.zoom_id
                    }
                    formDataArray.push(iiu)
                }
            }
            console.log('表单', { phone: this.$route.query.phone, fk_id: id, course: formDataArray })

            courseSaveAlls({ phone: this.$route.query.phone, fk_id: id, course: formDataArray }
            ).then(async res => {
                if (res.code == 200) {
                    console.log(res)
                    console.log('上传', this.filepath2li)
                    for (let i = 0; i < this.radio; i++) {
                        console.log('是否有名字：', !!this.ruleForm[i].fileName[0].filepath)
                        if (this.ruleForm[i].fileName[0].filepath) {
                            await this.$refs.upload2[i].putFile(this.ruleForm[i].fileName)
                        }
                        // await this.$refs.upload2[i].putFile(this.filepath2li[i])
                    }
                    this.$router.replace('/user/IntelligentTestUsers')
                }
            })
        },
        handleAvatar(file, fileList, index) {
            this.ruleForm[index].imageUrl = URL.createObjectURL(file.raw)
            if (this.ruleForm[index].imageUrl) {
                console.log('有上传的图片')
                this.$refs[`ruleForm${index + 1}`][0].clearValidate('image')
                delete this.$refs[`ruleForm${index + 1}`][0].rules.image
                console.log(this.$refs[`ruleForm${index + 1}`][0].rules)
            }
        },
        // 显示报表弹窗
        showDig() {
            this.showQuestionAnswerList = []
            this.dialogTableVisible = true
            this.getGroupQuestionList()
        },
        getAnswerSheetData() {
            var objData1 = {
                respondent_id: this.$route.query.respondent_id
            }
            console.log('isZoom1', this.isZoom)
            if (this.isZoom) {
                objData1.group_id = this.options[this.value].group_id
            }
            console.log('objData1', objData1)
            getAnswerSheet(objData1).then(res => {
                console.log('答题纸', res)
                for (let i = 0; i < res.data.length; i++) {
                    for (let j = 0; j < this.questionList.length; j++) {
                        if (this.questionList[j].unid == res.data[i].question_group_id) {
                            this.questionList[j].remark = res.data[i].remark
                            for (let l = 0; l < res.data[i].options.length; l++) {
                                for (let k = 0; k < this.questionList[j].options.length; k++) {
                                    if (res.data[i].options[l].includes(this.questionList[j].options[k].unid)) {
                                        this.questionList[j].options[k].isChecked = true
                                    }
                                }
                            }
                            this.showQuestionAnswerList.push(this.questionList[j])
                        }
                    }
                }
                console.log('showQuestionAnswerList>>>>>>>>>>>>>', this.showQuestionAnswerList)
            })
        },
        getGroupQuestionList() {
            var objData2 = {
                group_id: this.$route.query.group_id
            }
            console.log('isZoom2', this.isZoom)
            if (this.isZoom) {
                console.log('进来')
                objData2.group_id = this.options[this.value].group_id
            }
            console.log('objData2', objData2)
            getQuestionInfos(objData2).then(res => {
                this.questionList = res.data
                console.log('问题及选项', this.questionList)
                this.getAnswerSheetData()
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.main-content{
    padding: 36px 36px;
    width: 100%;
    background: #F0F2F5;;
    box-sizing: border-box;
    .main-content-top{
        display: flex;
        height: 310px;
        .userInfo{
            min-width: 360px;
            height: 100%;
            box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.16);
            border-radius: 10px;
            background: #ffffff;
        }
       .analysis{
             flex: 2;
            height: 100%;
            box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.16);
            margin-left: 30px;
            border-radius: 10px;
            background: #ffffff;

        }
    }
    .main-content-bottom{
        margin-top: 20px;
        width: 100%;
        box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.16);
        border-radius: 10px;
        background: #ffffff;
    }
}
    .title{
        width: 100%;
        height: 45px;
        font-size: 14px;
        color: #303133;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding:0 24px;
        box-sizing: border-box;
        border-bottom: 1px solid #E9E9E9;
        font-weight: bold;
    }
   .userInfo{
       .info{
        height: 100%;
        width: 100%;
        padding: 24px;
        box-sizing: border-box;
        .info-item{
            display: flex;
            height: 40px;
            align-items: center;
        }
    }
}
.analysis{
    .analysis-content{
    display: flex;
      height: 265px;
      width: 100%;
    }
    .noFen {
         width: 100%;
        padding: 20px;
        .showDig2{
            width: 100%;
            color: #409EFF;
             cursor: pointer;
            text-align: right;
            margin-bottom: 10px;
        }
        .bottomBtn {
            width: 100%;
            text-align: right;
            .saveBtn {
                margin: 15px 0;
            }
        }

    }

    .canvns{
        height: 265px;
        width: 400px;
    }
    .collapse{
        padding-right: 24px;
        margin-top: 20px;
        box-sizing: border-box;
        height: 100%;
        flex: 1;
        margin-left: 40px;
        .showDig{
            text-align: right;
             color: #409EFF;
             cursor: pointer;
        }
        .showCollapse{
            height: 200px;
            overflow: auto;
            margin-top: 20px;
        }
        .el-collapse{
            border: none;
        }
    }
}
.main-content-bottom{
    .drainage{
        padding: 24px;
        box-sizing: border-box;
        .curriculumNum{
          display: flex;
          align-items:center;
          .courseNum{
              margin-left:20px;

          }
        }
        .course{
            display: flex;
            width: 100%;
            margin-top: 20px;
            .courseItem{
                flex: 1;
                padding: 10px;
                .tip{
                    font-size: 12px;
                    color: #909399;
                    padding-left: 100px;
                    box-sizing: border-box;
                    margin-bottom: 10px;
                }
            }
        }
    }
}

  .avatar-uploader .el-upload {

    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
     border: 1px dashed #d9d9d9;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .tipsText {
      font-size: 14px;
      color: rgb(241, 105, 105);
      margin-top: 5px;
  }
</style>
